package com.zj.java21demo.filter;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zj.java21demo.entity.TUser;
import com.zj.java21demo.mapper.TUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @Version 1.0.0
 * @Date 2024/2/28 22:00
 * @Created by zhangjun
 */
@Slf4j
@Service
@AllArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

//    private IMemberService iMemberService;
//
//    private ThreadPoolConfig threadPoolConfig;

    private TUserMapper tUserMapper;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectOne(Wrappers.<TUser>lambdaQuery()
                .eq(TUser::getAccount,account)
                .eq(TUser::getIsActive, 1));

        if(tUser == null) {
            log.info("登录用户：{} 不存在.", account);
            throw new UsernameNotFoundException("登录用户：" + account + " 不存在");
        }else {
            // 1表示可用
//            boolean isenabled = user.getEnabled() == 1;
            /**
             * ，任何非零的整数值都会被视为 true，而 0 会被视为 false。
             */
            //模拟系统权限列表
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            return new org.springframework.security.core.userdetails.User(
                    tUser.getAccount(),
                    tUser.getPassword(),
                    true,
                    true,
                    true,
                    true,
                    authorities//权限列表
            );
        }


        // 记录最后一次登陆时间以及登陆IP
//        AsyncManager.me().execute(new TimerTask() {
//            @Override
//            public void run() {
//                iMemberService.update()
//                        .set("last_login_time", LocalDateTime.now())
//                        .set("last_login_ip", IpUtils.getHostIp())
//                        .eq("id", member.getId())
//                        .update();
//            }
//        });
//        return new LoginUserDetail(member, Collections.emptySet());
    }

}
